﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Odyssey.Linq;
using Odyssey.Web.Models;
using SunTzu.Web;
using Rea.Web.Models;

namespace Odyssey.Web.Controllers
{
    public class VisitorController : FrontBaseController
    {
        [Login]
        public ActionResult New()
        {
            ViewData.Model = db.form_visitors.FirstOrDefault(c => c.AccountId == LoginHelper.CurrentUserId)
                ?? new form_visitor();
            return View();
        }

        [Login]
        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreateVisitor(int? id)
        {
            form_visitor visitor = db.form_visitors.FirstOrDefault(c => c.AccountId == LoginHelper.CurrentUserId)
                ?? new form_visitor();
            HTMLHelper.BindModel(visitor);
            visitor.AccountId = LoginHelper.CurrentUserId;
            if (visitor.SaveOrUpdate())
            {
                SetMessage("保存成功！");
            }

            return RedirectToAction("New");
        }

        public ActionResult Register()
        {
            BindTopNavigation();
            BindContryList();
            BindCardType();

            return View();
        }

        private void BindContryList()
        {
            var countries = GetTable<tb_country>().OrderBy(item => item.name).ToList();

            List<SelectListItem> items = new List<SelectListItem>();
            foreach (tb_country country in countries)
            {
                items.Add(new SelectListItem { Text = country.name, Value = country.name, });
            }
            ViewBag.CountryList = items;
        }

        private void BindCardType()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Common:CardType".GetResourceText(), Value = "身份证" });
            ViewBag.CardTypeList = items;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(VisitorModel visitorModel)
        {
            tb_visitor visitor = new tb_visitor();
            HTMLHelper.BindModel(visitor);
            visitor.xingzhi = Request["xingzhi"];
            visitor.FavoriteProduct = Request["FavoriteProduct"];
            visitor.ServiceRequirement = Request["ServiceRequirement"];
            visitor.Media = Request["Media"];
            visitor.HowYouKnowUs = Request["HowYouKnowUs"];
            visitor.CreateDate = DateTime.Now;
            visitor.UpdateDate = DateTime.Now;
            visitor.SaveOrUpdate();
            return Redirect("/");
        }
    }
}
